iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0

昨天我們完成了下拉選單元件,
今天我們來做單選的radio元件,
一樣在element下面增加base-radio

ng g component base-radio

然後在main的設定檔裡面增加一組範例如下

        {
            name: 'radio1',
            cname: '單選1',
            inputType: 'radio',
            placeholder: '',
            required: true,
            defaultValue: '1',
            options: [
                { label: '選項1', value: '1' },
                { label: '選項2', value: '2' },
                { label: '選項3', value: '3' },
            ]
        }

這邊要注意的是radio不需要placeholder,
這樣我們把FieldSetting裡面的placeholder改成非必填好了

export interface FieldSetting
{
    name: string;
    cname: string;
    inputType: string;
    placeholder?: string; // 非必填加個問號
    required: boolean;
    defaultValue?: string | undefined;
    options?: OptionItem[];
}

接下來一樣在field.component.html增加一組給radio的模板

  <div *ngSwitchCase="'radio'">
    <app-base-radio
      [fieldSetting]="fieldSetting"
      [fieldObj]="fieldObj"
    ></app-base-radio>
  </div>

這邊來開始寫base-radio.component的內容,
由於radio都是數個type=radio的input組成,
相同的name會綁為同一組,
我們這邊沿用options為設定檔的規則,
radio會有幾個需要的參數

  • type 這個必定為radio
  • name 同樣的name視為同一組,這邊會使用fieldSetting.name
  • value 選取這個radio對應的數值 這邊使用fieldSetting.options下的value
  • ngModel 熟悉的雙向綁定
  • change 異動時要更新回fieldObj
  • 另外有顯示文字的部分 使用fieldSetting.options下的label

綜合以上條件,
這次寫的跟前面的base有點些微不同

// base-radio.component.html

<div>
  <label *ngFor="let option of fieldSetting?.options">
    <input
      type="radio"
      [name]="fieldSetting.name"
      [value]="option.value"
      [(ngModel)]="value"
      (change)="valueChange(option.value)"
    />
    <span>{{ option.label }}</span>
  </label>
</div>

// base-radio.component.ts

    @Input() fieldSetting!: FieldSetting;
    @Input() fieldObj!: any;
    value!: string;

    constructor() { }

    ngOnInit(): void
    {
        this.value = this.fieldObj[this.fieldSetting.name];
    }

    valueChange()
    {
        this.fieldObj[this.fieldSetting.name] = value;
    }

以上是今天的單選元件的部分,
由於今天的篇幅比較短,
可以來整理一下之後可能要寫的部分,
明天就是多選選單的部分,
多選會比較特別,因為數值可能是複數,也許會用陣列,或者用特殊格式的字串
然後有個部分會接連著處理,
就是要考慮到欄位檢核的部分,
由於檢核會使用到formControl,
所以再開始寫檢核前應該會有一次重構,
如果前面寫的部分有那裡有問題也請大家多留言,
感謝各位

今日程式:day08


上一篇
第7天 下拉選單元件
下一篇
第9天 多選checkbox元件
系列文
簡單的事 最困難-Angular動態Form元件14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言